/**
 * myTreeSelect.js
 * v 1.0.0
 * Author:wendy (QQ51594)
 * Date:2023-2-14
 *
 * 使用方法
 * 1、直接html配置,可配置多个，数据直接从url中读取
 * html:
 * <input type="text" url="getDataApi" class="layui-hide" lay-skin="mytreeselect" value="1" placeholder="请选择节点">
 * js:
 * layui.treeSelect.render({});
 *
 * 2。js配置
 * html:
 * <input type="text" class="layui-hide" id="treeselect1" value="5" placeholder="请选择节点">
 * js:
 *  treeSelect.render({
            elem: '#treeselect1',
            data: {},
            init: '5',
            click: function (d) {
                //console.log(d);
            }
        });

 *数据格式示例：
 *
 *  var datas =
 [{
                    "children": [
                        {"title": "留言列表", "text": "留言列表", "id": 5, "turn": true},
                        {"title": "发表留言", "text": "发表留言", "id": 6, "turn": true}
                    ],
                    "title": "评论(无法选择)", "text": "评论", "id": 4, "turn": false
                }];
 */
layui.define(["jquery", 'myTree'], function (exports) {

    var model_name = 'myTreeSelect',
        mytreeselect_elem = "input[lay-skin='mytreeselect']",
        MyTreeInput = "mytreeselect-input-",
        $ = layui.jquery, tree = layui.myTree;

    var obj = {
        v: '1.0.0',
        render: function (opt) {
            var options = {
                elems: mytreeselect_elem
            }
            var _this = this;
            options = $.extend(options, opt);
            if (options.elem) {
                var myselecttree = $(options.elem);
                myselecttree.options = options;
                _this.init(myselecttree);
            } else if (options.elems) {
                $.each($(options.elems), function () {
                    var myselecttree = $(this);
                    myselecttree.options = options;
                    myselecttree.options.url = $(this).attr('url');
                    myselecttree.options.data = $(this).attr('data');
                    myselecttree.options.init = $(this).attr('value');
                    _this.init(myselecttree);
                });
            }
            return this;
        }
        , init: function (_that) {
            _that.options.tmp = new Date().getTime(),
                _that.options.treeInputId = MyTreeInput + _that.options.tmp;
            this.input(_that);//初始化html

            //从url中取数据
            if (_that.options.url != undefined) {
                $.ajaxSetup({async: false});//同步执行
                layui.$.get(_that.options.url, {tmp: _that.options.tmp}, function (result) {
                    var mytree = tree.render({
                        elem: '#TreeDiv-' + _that.options.tmp
                        , tmp: _that.options.tmp
                        , treeInputId: _that.options.treeInputId
                        , data: result
                        , click: function (obj) {
                            $(_that).val(obj.data.id);//赋保存值value
                            $("#" + obj.options.treeInputId).val(obj.data.text);//赋显示值
                            if (_that.options.click) {
                                _that.options.click(obj);//如果有回调，调用。
                            }
                            //已选中，关闭窗口
                            $('#LayTree-' + obj.options.tmp).removeClass('layui-form-selected').addClass('layui-unselect');
                        }
                    });
                    //赋初始值
                    $("#" + _that.options.treeInputId).val(mytree.init(_that.options.init, '#TreeDiv-' + _that.options.tmp));
                });
            } else if (typeof(_that.options.data) == 'object') {//如果url为空，传入的有data值
                var mytree = tree.render({
                    elem: '#TreeDiv-' + _that.options.tmp
                    , tmp: _that.options.tmp
                    , treeInputId: _that.options.treeInputId
                    , data: _that.options.data
                    , click: function (obj) {
                        $(_that).val(obj.data.id);
                        $("#" + obj.options.treeInputId).val(obj.data.text);
                        if (_that.options.click) {
                            _that.options.click(obj);//如果有回调，调用。
                        }
                        //已选中，关闭窗口
                        $('#LayTree-' + obj.options.tmp).removeClass('layui-form-selected').addClass('layui-unselect');
                    }
                });
                $("#" + _that.options.treeInputId).val(mytree.init(_that.options.init, '#TreeDiv-' + _that.options.tmp));
            } else {
                console.info("myTreeSelect.js[111]:data and url 不能同时为空")
            }
        }
        , input: function (elem) {
            $(elem).hide();//隐藏原始窗口
            var tmp = elem.options.tmp;
            var $treeDiv = $('<div>').attr({id: 'LayTree-' + tmp}).addClass('layui-treeselect layui-unselect layui-form-select'),
                placeholder = $(elem).attr('placeholder'),
                $treeTitle = $('<div class="layui-select-title">').attr('id', 'mytreeselect-title-' + tmp),
                value = $(mytreeselect_elem).val(),
                $treeInput = $('<input>').attr({placeholder: placeholder, readonly: 'readonly', type: 'text', value: value, id: MyTreeInput + tmp})
                    .addClass('layui-input layui-unselect').click(function () {
                    }),
                $LayuiTree = $('<div>').addClass('layui-anim layui-tree-box layui-anim-upbit layui-box').attr({id: 'LayTree--' + tmp});
            $LayuiTree.append($('<div>').addClass("layui-tree").attr({id: 'TreeDiv-' + tmp}));
            $treeDiv.append($treeTitle.append($treeInput).append('<i class="layui-edge"></i>')).append($LayuiTree);
            $(elem).after($treeDiv);
            this.titleToggle(tmp);
            return this;
        }
        , style: function () {
            var style = '<style>' +
                '.layui-treeselect .layui-tree-box{' +
                '   display: none;\
                    position: absolute;\
                    left: 0;\
                    top: 42px;\
                    padding: 5px 0px 0px 5px;\
                    z-index: 999;\
                    min-width: 100%;\
                    border: 1px solid #d2d2d2;\
                    min-height: 200px;\
                    max-height: 300px;\
                    overflow-y: auto;\
                    background-color: #fff;\
                    border-radius: 2px;\
                    box-shadow: 0 2px 4px rgba(0,0,0,.12);\
                    box-sizing: border-box;' +
                '}' +
                '.layui-tree{position: absolute;top:0px;left:0px;border:0px}' +
                '.layui-form-selected .layui-tree-box{display: inline-block}' +
                '</style>';
            $('head').append(style);
        }, titleToggle: function (tmp) {
            //选中和关闭之间切换
            this.event('click', '#mytreeselect-title-' + tmp, function () {
                var $LayuiTree = $('#LayTree-' + tmp);
                if ($LayuiTree.hasClass('layui-form-selected')) {
                    $LayuiTree.removeClass('layui-form-selected').addClass('layui-unselect');
                } else {
                    $LayuiTree.addClass('layui-form-selected').removeClass('layui-unselect');
                }
            });
            return this;
        }, event: function (evt, elem, func) {
            $('body').on(evt, elem, func);
        }
    };

    obj.style();
    exports(model_name, obj);
})